import os
import random
import subprocess
from datetime import datetime
from flask import Flask, request, jsonify

app = Flask(__name__)
OUTPUT_DIR = r"D:\facehuman\result"

def generate_video(video_list_a, video_list_b, insert_time):
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    output_path = os.path.join(OUTPUT_DIR, f"output_{timestamp}.mp4")

    random.shuffle(video_list_a)

    # 创建临时concat列表文件（使用绝对路径）
    concat_list = "concat_list.txt"
    with open(concat_list, "w") as f:
        f.write("\n".join([f"file '{os.path.abspath(f)}'" for f in video_list_a]))

    overlay_video = random.choice(video_list_b)

    # 修正后的FFmpeg命令
    ffmpeg_cmd = [
        'ffmpeg',
        '-f', 'concat',
        '-safe', '0',
        '-i', concat_list,
        '-i', overlay_video,

        # 修正的过滤器语法
        '-filter_complex',
        f'''
        [0:v]setpts=PTS-STARTPTS[main];
        [1:v]scale=iw/4:ih/4,
            enable='gte(t,{insert_time})'
            [overlay];
        [main][overlay]overlay=W-w-10:H-h-10[merged];
        [0:a]aresample=async=1[audio]
        ''',

        '-map', '[merged]',
        '-map', '[audio]',
        '-c:v', 'libx264',
        '-preset', 'fast',
        '-c:a', 'aac',
        '-y',
        output_path
    ]

    try:
        # 显示完整命令用于调试
        print("执行命令：", ' '.join(ffmpeg_cmd))
        subprocess.run(
            ffmpeg_cmd,
            check=True,
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE
        )
    except subprocess.CalledProcessError as e:
        error_msg = e.stderr.decode('utf-8', errors='ignore')
        os.remove(concat_list)
        raise RuntimeError(f"FFmpeg执行失败: {error_msg}")

    os.remove(concat_list)
    return output_path

@app.route('/generate', methods=['POST'])
def generate():
    try:
        data = request.json
        video_list_a = [os.path.abspath(f) for f in data.get('list_a', [])]
        video_list_b = [os.path.abspath(f) for f in data.get('list_b', [])]
        insert_time = float(data.get('insert_time', 0))

        # 增强路径验证
        for f in video_list_a + video_list_b:
            if not os.path.exists(f):
                return jsonify({"error": f"文件不存在: {f}"}), 400

        output_path = generate_video(video_list_a, video_list_b, insert_time)
        return jsonify({
            "status": "success",
            "path": output_path,
            "message": f"视频已生成至 {output_path}"
        })

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

if __name__ == '__main__':
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    video_list_a = ['D://human/20250303/1.mp4','D://human/20250303/2.mp4']
    video_list_b = ['D://human/20250303/s.mp4']
    generate_video(video_list_a, video_list_b, 2.0)
    # app.run(host='0.0.0.0', port=5000)
